<template>
  <div>
    <el-card class="sur-card">
      <div class="sur-card-title" slot="header">
        <span>编辑商品</span>
      </div>

      <el-row type="flex" justify="center">
        <el-col span="18">
          <el-form :model="itemModel" label-position="left" label-width="120px">
            <el-form-item label="商品名称">
              <el-input
                v-model="itemModel.itemName"
                style="width: 450px;"
                maxlength="55"
                show-word-limit
                placeholder="请输入产品名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品编码">
              <el-input
                style="width: 450px;"
                v-model="itemModel.itemCode"
                placeHolder="请输入商品编码"
                maxlength="55"
                show-word-limit
              ></el-input>
            </el-form-item>
            <!-- <el-form-item label="副标题">
              <el-input
                style="width: 450px;"
                v-model="itemModel.caption"
                placeHolder="请输入副标题"
              ></el-input>
            </el-form-item>
            <el-form-item label="关键词">
              <el-input
                style="width: 450px;"
                v-model="itemModel.keywords"
                placeHolder="请输入关键词"
              ></el-input>
            </el-form-item>
              <el-form-item label="商品类型">
              <el-select v-model="itemModel.catId">
                <el-option
                  v-for="cat in categories"
                  :key="cat.id"
                  :label="cat.catName"
                  :value="cat.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品标签">
              <el-input
                style="width: 450px;"
                v-model="itemModel.tags"
                placeHolder="请输入该字段"
              ></el-input>
              <div class="hint-text">请输入标签，以逗号分隔</div>
            </el-form-item>-->
            <el-form-item label="商品分类">
              <el-select v-model="itemModel.catId">
                <el-option
                  v-for="cat in categories"
                  :key="cat.id"
                  :label="cat.catName"
                  :value="cat.id"
                ></el-option>
              </el-select>
            </el-form-item>

            <!--  <el-form-item label="销售状态">
              <el-switch
                v-model="itemModel.onSale"
                active-text="上架"
                inactive-text="下架"
              >
              </el-switch>
            </el-form-item>-->
            <el-form-item label="主图">
              <el-upload
                style="display: inline-block;"
                :http-request="handleMainImgUploadFile"
                :show-file-list="false"
              >
                <el-button size="small" type="primary" icon="el-icon-picture"
                  >点击上传</el-button
                >
              </el-upload>
              <hover-mask v-if="itemModel.mainImage">
                <!-- 默认插槽 -->
                <el-image
                  :src="itemModel.mainImage"
                  fit="contain"
                  style="height: 80px;width: 80px;"
                ></el-image>
                <!-- action插槽 -->
                <template v-slot:action>
                  <i class="el-icon-delete" @click="onDeleteMainImage"></i>
                </template>
              </hover-mask>
            </el-form-item>
            <el-form-item label="轮播素材">
              <el-button
                size="small"
                icon="el-icon-edit"
                @click="onEditCarouseMedia"
                >编辑素材</el-button
              >
            </el-form-item>
            <el-form-item label="排序">
              <el-input-number
                v-model="itemModel.sort"
                placeHolder="请输入排序"
              ></el-input-number>
            </el-form-item>
            <el-form-item>
              <el-button type="danger" style="width: 260px;" @click="onSaveItem"
                >保存</el-button
              >
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
    <item-media-editor
      :show.sync="editCarouselMedia"
      :carousel-medias="itemModel.carouselMedias"
      v-on:onCarouseMediaSaved="onCarouseMediaSaved"
    ></item-media-editor>
  </div>
</template>

<script>
import {
  getUploadItemMediaToken,
  uploadFileToAliOss
} from "@/api/admin-api/FileApi";
import HoverMask from "@/components/HoverMask";
import ItemMediaEditor from "@/components/ItemProp/ItemMediaEditor";
import { addItem, getItem, updateItemById } from "@/api/admin-api/ItemApi";
import { listAllCategory } from "@/api/admin-api/CagegoryApi";
export default {
  name: "ItemEdit",
  components: {
    HoverMask,
    ItemMediaEditor
  },
  props: {
    itemId: []
  },
  data() {
    return {
      categories: [],
      editCarouselMedia: false,
      itemModel: {
        catId: null,
        onSale: false,
        itemName: null,
        itemCode: null,
        caption: null,
        keywords: null,
        mainImage: null,
        carouselMedias: [],
        carouselMediasJson: "[]",
        itemType: null,
        tags: null,
        visitedNum: null,
        sort: null
      }
    };
  },
  methods: {
    onSaveItem() {
      this.$loading();
      if (this.itemModel.id) {
        // 更新
        updateItemById(this.itemModel).then(() => {
          this.$message.success("保存成功");
          this.loadBasicItem();
          this.$loading().close();
        });
      } else {
        // 保存新的
        addItem(this.itemModel).then(() => {
          this.$loading().close();
          this.$message.success("保存成功");
          this.$router.back();
        });
      }
      //保存商品信息
      console.log("this.itemModel", this.itemModel);
    },
    onCarouseMediaSaved(mediaJson) {
      console.log(mediaJson);
      this.itemModel.carouselMediasJson = mediaJson;
    },
    onDeleteMedia(row) {
      console.log(row);
    },
    onEditCarouseMedia() {
      console.log(
        "JSON.parse(this.carouselMediasJson)",
        this.itemModel.carouselMediasJson
      );
      this.itemModel.carouselMedias = JSON.parse(
        this.itemModel.carouselMediasJson
      );
      this.editCarouselMedia = true;
    },
    onDeleteMainImage() {
      this.itemModel.mainImage = "";
    },
    loadAllCategories() {
      return new Promise(resolve => {
        listAllCategory().then(data => {
          // this.categories = data.records;
          resolve(data.records);
        });
      });
    },
    handleMainImgUploadFile({ file }) {
      getUploadItemMediaToken().then(uploadToken => {
        // 上传文件
        const formData = new FormData();
        const fileKey = uploadToken.dir.concat(file.name);
        formData.append("key", fileKey);
        formData.append("policy", uploadToken.policy);
        formData.append("OSSAccessKeyId", uploadToken.ossAccessKeyId);
        formData.append("success_action_status", "200");
        formData.append("signature", uploadToken.signature);
        formData.append("file", file);
        // 上传至阿里云oss
        this.$loading();
        console.log("上传地址", uploadToken.fileHost);
        uploadFileToAliOss(uploadToken.fileHost, formData)
          .then(() => {
            this.itemModel.mainImage = "https://asset.fanghaowu.com/" + fileKey;
            this.$loading().close();
          })
          .catch(() => {
            this.$loading().close();
          });
      });
    },
    loadBasicItem() {
      getItem(this.itemId).then(data => {
        this.itemModel = data;
      });
    }
  },
  async mounted() {
    this.categories = await this.loadAllCategories();
    console.log("itemId", this.itemId);
    if (this.itemId) {
      // 加载商品信息
      this.loadBasicItem();
    }
  }
};
</script>

<style scoped></style>
